﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using XEvents.Library;

namespace ExtendedEventsManager
{
    public partial class AddTargetToSessionForm : Form
    {
        private class FieldBinder
        {
            public FieldBinder(Column field)
            {
                _name = field.Name;
                _required = field.Required;
            }

            private string _value = string.Empty;
            private string _name = string.Empty;
            private string _typename = string.Empty;
            private string _columntype = string.Empty;
            private bool _required = false;

            public string Value
            {
                get { return _value; }
                set { _value = value; }
            }

            public string Name
            {
                get { return _name; }
            }

            public bool Required
            {
                get { return _required; }
            }

        }

        private SessionEditorForm _parent;
        private bool _optionerror = true;

        List<FieldBinder> _fields = new List<FieldBinder>();
        BindingSource bs = new BindingSource();

        public AddTargetToSessionForm(SessionEditorForm parent)
        {
            InitializeComponent();
            _parent = parent;
            dgv_TargetOptions.AutoGenerateColumns = false;
            BindPackages();
            this.Text = "Target Editor (" + parent.SessionName + ")";
        }

        public AddTargetToSessionForm(SessionEditorForm parent, EventSessionTarget sessiontarget)
        {
            InitializeComponent();
            _parent = parent;
            dgv_TargetOptions.AutoGenerateColumns = false;
            BindPackages();
            this.Text = "Target Editor (" + parent.SessionName + ")";
            BindSessionDataToForm(sessiontarget);
        }

        private void BindSessionDataToForm(EventSessionTarget sessiontarget)
        {
            foreach (Package p in _parent.Session.SqlServer.MetaData.Packages)
            {
                if (p.Name == sessiontarget.Name.Split('.').ElementAt(0))
                {
                    cmbx_Package.SelectedItem = p;
                    foreach (Target t in p.Targets)
                    {
                        if (t.Name == sessiontarget.Name.Split('.').ElementAt(1))
                            cmbx_Target.SelectedItem = t;
                    }
                }
            }

            for (int i = 0; i < dgv_TargetOptions.Rows.Count; i++)
            {
                DataGridViewRow dgvr = dgv_TargetOptions.Rows[i];

                DataGridViewTextBoxCell namecell = (DataGridViewTextBoxCell)dgvr.Cells["dgvTargetOptions_Name"];
                DataGridViewTextBoxCell valuecell = (DataGridViewTextBoxCell)dgvr.Cells["dgvTargetOptions_Value"];

                if (sessiontarget.OptionsString.Contains(namecell.Value.ToString()))
                {
                    foreach (EventSessionTargetOption option in sessiontarget.Options)
                    {
                        if (option.Name == namecell.Value.ToString())
                            _fields[i].Value = option.Value;
                    }
                }

            }
            bs.ResetBindings(true);
        }

        public AddTargetToSessionForm()
        {
            InitializeComponent();
        }

        private void PopulateTargets()
        {
            List<Target> _targets = ((Package)cmbx_Package.SelectedItem).Targets;
            cmbx_Target.DataSource = _targets;
            cmbx_Target.ValueMember = "Name";
            cmbx_Target.DisplayMember = "Name";
        }

        private void BindPackages()
        {
            List<Package> lp = _parent.Session.SqlServer.MetaData.Packages.PackagesWithTargets;
            cmbx_Package.DataSource = lp;
            cmbx_Package.ValueMember = "Name";
            cmbx_Package.DisplayMember = "Name";
        }

        private void cmbx_Target_SelectedIndexChanged(object sender, EventArgs e)
        {
            Target t = (Target)cmbx_Target.SelectedItem;
            lbl_Description.Text = t.Description;

            _fields = new List<FieldBinder>();

            foreach (Column f in t.Fields)
            {
                _fields.Add(new FieldBinder(f));
            }
            bs.DataSource = _fields;
            dgv_TargetOptions.DataSource = bs;
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            EventSessionTarget st = new EventSessionTarget();
            st.Name = cmbx_Package.Text+"."+cmbx_Target.Text;
            
            _optionerror = false;
            foreach (DataGridViewRow row in dgv_TargetOptions.Rows)
            {
                DataGridViewTextBoxCell nameCell = (DataGridViewTextBoxCell)row.Cells["dgvTargetOptions_Name"];
                DataGridViewTextBoxCell valueCell = (DataGridViewTextBoxCell)row.Cells["dgvTargetOptions_Value"];
                DataGridViewCheckBoxCell requiredCell = (DataGridViewCheckBoxCell)row.Cells["dgvTargetOptions_Required"];

                if (Convert.ToBoolean(requiredCell.Value))
                {
                    if (valueCell.Value == null || valueCell.Value.ToString() == string.Empty)
                    {
                        MessageBox.Show("The target option " + nameCell.Value.ToString() + " must have a Value set for this target!", "Missing Target Option Value", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _optionerror = true;
                    }
                    else
                    {
                        st.Options.Add(new EventSessionTargetOption(nameCell.Value.ToString(), valueCell.Value.ToString()));
                    }
                }
                else
                {
                    if (!(valueCell.Value == null))
                    {
                        if (!(valueCell.Value.ToString() == string.Empty))
                        {
                            st.Options.Add(new EventSessionTargetOption(nameCell.Value.ToString(), valueCell.Value.ToString()));
                        }
                    }
                }
            }

                if (!_optionerror)
                {
                    _parent.TargetBindingSource.Add(st);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
        }

        private void cmbx_Package_SelectedIndexChanged(object sender, EventArgs e)
        {
            PopulateTargets();
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
